// pages/merchant/cashier/index.js
const apiService = require('../../../utils/api.js');

Page({
  data: {
    // 今日营收统计
    todayRevenue: {
      total: 0,
      orders: 0,
      avgOrder: 0,
      payments: 0
    },
    
    // 支付方式
    selectedPayment: '',
    paymentAmount: '',
    
    // 订单信息
    serviceTypes: ['洗浴服务', '美容服务', '寄养服务', '设备使用', '其他服务'],
    serviceIndex: 0,
    customerInfo: '',
    orderNote: '',
    
    // 收款记录
    paymentRecords: [],
    
    // 处理状态
    isProcessing: false,
    
    // 支付结果弹窗
    showPaymentResultModal: false,
    paymentResult: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('收银台页面加载', options);
    this.loadTodayRevenue();
    this.loadPaymentRecords();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadTodayRevenue();
    this.loadPaymentRecords();
  },

  /**
   * 加载今日营收
   */
  async loadTodayRevenue() {
    try {
      // 模拟今日营收数据，实际项目中应该调用API
      const mockRevenue = {
        total: 2580,
        orders: 18,
        avgOrder: 143,
        payments: 22
      };

      this.setData({ todayRevenue: mockRevenue });
      
    } catch (error) {
      console.error('加载今日营收失败:', error);
    }
  },

  /**
   * 加载收款记录
   */
  async loadPaymentRecords() {
    try {
      // 模拟收款记录数据，实际项目中应该调用API
      const mockRecords = [
        {
          paymentId: 'pay_001',
          amount: 88,
          method: 'wechat',
          methodText: '微信支付',
          status: 'success',
          statusText: '成功',
          statusClass: 'success',
          paymentTime: '14:30:25',
          customerInfo: '张小明',
          transactionId: 'WX20240125001'
        },
        {
          paymentId: 'pay_002',
          amount: 200,
          method: 'alipay',
          methodText: '支付宝',
          status: 'success',
          statusText: '成功',
          statusClass: 'success',
          paymentTime: '15:45:12',
          customerInfo: '李小红',
          transactionId: 'ALI20240125002'
        },
        {
          paymentId: 'pay_003',
          amount: 50,
          method: 'cash',
          methodText: '现金支付',
          status: 'success',
          statusText: '成功',
          statusClass: 'success',
          paymentTime: '16:20:08',
          customerInfo: '王小强',
          transactionId: 'CASH20240125003'
        }
      ];

      this.setData({ paymentRecords: mockRecords });
      
    } catch (error) {
      console.error('加载收款记录失败:', error);
    }
  },

  /**
   * 选择支付方式
   */
  onSelectPayment(e) {
    const method = e.currentTarget.dataset.method;
    this.setData({ selectedPayment: method });
  },

  /**
   * 金额输入
   */
  onAmountInput(e) {
    this.setData({ paymentAmount: e.detail.value });
  },

  /**
   * 选择快速金额
   */
  onSelectAmount(e) {
    const amount = e.currentTarget.dataset.amount;
    this.setData({ paymentAmount: amount });
  },

  /**
   * 服务类型选择
   */
  onServiceChange(e) {
    this.setData({ serviceIndex: e.detail.value });
  },

  /**
   * 客户信息输入
   */
  onCustomerInfoInput(e) {
    this.setData({ customerInfo: e.detail.value });
  },

  /**
   * 订单备注输入
   */
  onOrderNoteInput(e) {
    this.setData({ orderNote: e.detail.value });
  },

  /**
   * 处理支付
   */
  async onProcessPayment() {
    const { paymentAmount, selectedPayment, serviceTypes, serviceIndex, customerInfo, orderNote } = this.data;
    
    if (!paymentAmount || parseFloat(paymentAmount) <= 0) {
      wx.showToast({
        title: '请输入有效金额',
        icon: 'none'
      });
      return;
    }

    if (!selectedPayment) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none'
      });
      return;
    }

    this.setData({ isProcessing: true });

    try {
      // 模拟支付处理，实际项目中应该调用API
      const paymentResult = await this.mockProcessPayment();
      
      this.setData({
        paymentResult,
        showPaymentResultModal: true
      });

      // 如果支付成功，更新数据
      if (paymentResult.success) {
        this.updateRevenueData(paymentResult);
        this.addPaymentRecord(paymentResult);
        this.clearForm();
      }
      
    } catch (error) {
      console.error('支付处理失败:', error);
      wx.showToast({
        title: '支付失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isProcessing: false });
    }
  },

  /**
   * 模拟支付处理
   */
  async mockProcessPayment() {
    const { paymentAmount, selectedPayment, serviceTypes, serviceIndex, customerInfo, orderNote } = this.data;
    
    // 模拟网络请求延迟
    await new Promise(resolve => setTimeout(resolve, 2000));

    // 模拟支付结果（90%成功率）
    const isSuccess = Math.random() > 0.1;
    
    const methodTexts = {
      wechat: '微信支付',
      alipay: '支付宝',
      cash: '现金支付',
      balance: '余额支付'
    };

    if (isSuccess) {
      return {
        success: true,
        amount: paymentAmount,
        method: selectedPayment,
        methodText: methodTexts[selectedPayment],
        paymentTime: this.formatTime(new Date()),
        transactionId: `${selectedPayment.toUpperCase()}${Date.now()}`,
        serviceType: serviceTypes[serviceIndex],
        customerInfo: customerInfo || '匿名客户',
        orderNote: orderNote
      };
    } else {
      const errorMessages = [
        '网络连接失败',
        '支付超时',
        '余额不足',
        '系统繁忙，请稍后重试'
      ];
      
      return {
        success: false,
        message: errorMessages[Math.floor(Math.random() * errorMessages.length)]
      };
    }
  },

  /**
   * 更新营收数据
   */
  updateRevenueData(paymentResult) {
    const { todayRevenue } = this.data;
    const amount = parseFloat(paymentResult.amount);
    
    const newRevenue = {
      total: todayRevenue.total + amount,
      orders: todayRevenue.orders + 1,
      avgOrder: Math.floor((todayRevenue.total + amount) / (todayRevenue.orders + 1)),
      payments: todayRevenue.payments + 1
    };

    this.setData({ todayRevenue: newRevenue });
  },

  /**
   * 添加收款记录
   */
  addPaymentRecord(paymentResult) {
    const newRecord = {
      paymentId: 'pay_' + Date.now(),
      amount: paymentResult.amount,
      method: paymentResult.method,
      methodText: paymentResult.methodText,
      status: 'success',
      statusText: '成功',
      statusClass: 'success',
      paymentTime: paymentResult.paymentTime,
      customerInfo: paymentResult.customerInfo,
      transactionId: paymentResult.transactionId
    };

    const records = [newRecord, ...this.data.paymentRecords];
    this.setData({ paymentRecords: records });
  },

  /**
   * 清空表单
   */
  clearForm() {
    this.setData({
      paymentAmount: '',
      selectedPayment: '',
      customerInfo: '',
      orderNote: '',
      serviceIndex: 0
    });
  },

  /**
   * 关闭支付结果弹窗
   */
  onClosePaymentResultModal() {
    this.setData({ showPaymentResultModal: false });
  },

  /**
   * 格式化时间
   */
  formatTime(date) {
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${hours}:${minutes}:${seconds}`;
  },

  /**
   * 防止弹窗滚动穿透
   */
  preventTouchMove() {
    return false;
  }
});